﻿// <copyright file="StringHelpers.cs" company="Auros Ltd.">
//     Copyright (c) Auros Ltd. All rights reserved.
// </copyright>

namespace Auros.Categorisation
{
    using System.Collections.Generic;
    using umbraco.cms.businesslogic;

    /// <summary>
    /// Class containing string helper methods.
    /// </summary>
    internal class StringHelpers
    {
        /// <summary>
        /// Parses the dictionary key and returns the dictionary value.
        /// </summary>
        /// <param name="dictionaryKey">The dictionary item key.</param>
        /// <returns>Dictionary string value.</returns>
        public static string ParseDictionaryItem(string dictionaryKey, string defaultValue = null)
        {
            if (StringHelpers.DictionaryItemExists(dictionaryKey))
                return umbraco.library.GetDictionaryItem(dictionaryKey);

            return defaultValue ?? dictionaryKey;
        }

        /// <summary>
        /// Checks whether a dictionary item with the specified key exists.
        /// </summary>
        /// <param name="dictionaryKey">The dictionary key.</param>
        /// <returns>True if the dictionary item exists; otherwise false.</returns>
        public static bool DictionaryItemExists(string dictionaryKey)
        {
            return Dictionary.DictionaryItem.hasKey(dictionaryKey) && !string.IsNullOrEmpty(umbraco.library.GetDictionaryItem(dictionaryKey));
        }

        /// <summary>
        /// Converts string to integer list.
        /// </summary>
        /// <param name="csvString">The CSV string.</param>
        /// <param name="separator">The separator used within the string value.</param>
        /// <returns>List of integer items.</returns>
        public static IEnumerable<int> StringToIntList(string csvString, char separator = ',')
        {
            // Avoid errors if the string is empty or null.
            if (string.IsNullOrEmpty(csvString))
                yield break;

            // Split string.
            string[] split = csvString.Split(separator);

            int parsed;

            foreach (string n in split)
            {
                // Try and parse the string item.
                if (int.TryParse(n, out parsed))
                    yield return parsed;
            }
        }
    }
}